//
//  MM_UploadPicView.m
//  FootPad
//
//  Created by 张浩 on 2021/12/2.
//  Copyright © 2021 胶享悦. All rights reserved.
//

#import "MM_UploadPicView.h"
#import "MM_ImageButton.h"

@interface MM_UploadPicView ()

@property (nonatomic,strong) UIImageView *imageView;
@property (nonatomic,strong) MM_ImageButton *errorBtn;

@property (nonatomic, copy) MMUploadPicViewSuccessBlock successBlock;
@property (nonatomic, copy) MMUploadPicViewFailBlock    failBlock;
@property (nonatomic, copy) MMUploadPicViewTapClickBlock  tapPicBlock;
@property (nonatomic, copy) MMUploadPicViewTapDeleteBlock deletePicBlock;
@property (nonatomic, copy) MMUploadPicViewTapErrorBlock  errorPicBlock;

@end

@implementation MM_UploadPicView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        _imageView = [[UIImageView alloc]init];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
        _imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageTapClick)];
        [_imageView addGestureRecognizer:tap];
        [self addSubview:_imageView];
        
        _maskView = [[UIView alloc]init];
        _maskView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        [self addSubview:_maskView];
        
        _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleteBtn setImage:[UIImage imageNamed:@"bot_minus"] forState:UIControlStateNormal];
        [_deleteBtn addTarget:self action:@selector(deleteClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_deleteBtn];
        
        _errorBtn = [MM_ImageButton buttonWithType:UIButtonTypeCustom withSpace:5];
        [_errorBtn setTitle:@"重新上传" forState:UIControlStateNormal];
        _errorBtn.titleLabel.font = FONT(10);
        _errorBtn.buttonStyle = FPButtonImageTop;
        [_errorBtn setTitleColor:[ColorUtil colorWithHexadecimal:@"#ffffff"] forState:UIControlStateNormal];
        [_errorBtn setImage:[UIImage imageNamed:@"uploadPic"] forState:UIControlStateNormal];
//        _chooseBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [_errorBtn addTarget:self action:@selector(errorClick) forControlEvents:UIControlEventTouchUpInside];
//        _errorBtn.padding = 5;
        _errorBtn.hidden = YES;
        [self addSubview:_errorBtn];
        
        [self configSubViews];
    }
    return self;
}

- (void)setFrame:(CGRect)frame {
    
    [super setFrame:frame];
    
    if (CGRectEqualToRect(frame, CGRectZero)) {
        return;
    }
    
    [self configSubViews];
}

/**
 *  布局cell
 */
- (void)configSubViews {
    
    _imageView.frame = self.bounds;
    if (MMUploadViewTypeNone == self.imageModel.uploadStatusType) {
        _maskView.frame = self.bounds;
    }
    CGFloat space = 10.0;
    _deleteBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, space, space);
    CGFloat deleteBtnWH = 30;
    CGFloat deleteBtnX = 20;
    [_deleteBtn setFrame:CGRectMake(self.MM_w-deleteBtnX, 0, deleteBtnWH, deleteBtnWH)];
    
    CGFloat errorSpace = 5.0;
    _errorBtn.imageEdgeInsets = UIEdgeInsetsMake(errorSpace, errorSpace, errorSpace, errorSpace);
    CGFloat errorBtnWH = 50;
    CGFloat errorBtnX = self.MM_w/2.0  - errorBtnWH/2.0;
    CGFloat errorBtnY = self.MM_h/2.0 - errorBtnWH/2.0;
    [_errorBtn setFrame:CGRectMake(errorBtnX, errorBtnY, errorBtnWH, 36)];
}


/**
 *  布局视图
 *
 *  @param imageModel
 */
- (void)setImageModel:(MM_UploadImageModel *)imageModel {
    
    _imageModel = imageModel;
    
    if (imageModel == nil) {
        
        return;
    }
    
    if (imageModel.tempImage) {
        
        if (!stringIsEmpty(imageModel.img)) {
            self.maskView.hidden = YES;
            self.imageView.image = imageModel.tempImage;
        }else {
            
            if (imageModel.file_path) {
                self.maskView.hidden = YES;
                self.imageView.image = imageModel.tempImage;
            } else {
                self.maskView.hidden = NO;
                self.imageView.image = imageModel.tempImage;
            }
            
        }
        
    }else {
        
        self.maskView.hidden = YES;
        [self.imageView MM_setImageWithUrl:imageModel.img placeholderImage:[UIImage imageNamed:@""]];
//        [self.imageView JH_setImageWithUrl:imageModel.img placeholderImage:nil];
//        WS(weakSelf);
//        [_imageView sd_setImageWithURL:[Tools getImgUrlFullPathWithStr:imageModel.img] placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//
//            if (image) {
//                CGFloat h = image.size.height * ScreenW / image.size.width;
//                if (weakSelf.refreshSize) {
//                    weakSelf.refreshSize(h);
//                }
//            }
//        }];
    }
    
}

- (void)startUploadPic {
    
    WS(weakSelf);
    if (self.imageModel.tempImage == nil) {
        [MM_PublicHUD showStateText:@"请选择上传的图片！"];
        return;
    }
    
    _maskView.hidden = NO;
    _errorBtn.hidden = YES;
    // 初始化
    _maskView.frame = self.bounds;
    
    NSMutableDictionary *parmDic = [NSMutableDictionary dictionary];
    
    self.maskView.MM_w = weakSelf.MM_w;
    self.maskView.MM_x = 0;
    self.imageModel.uploadStatusType = MMUploadViewTypeUploading;//正在、上传

    [MM_Http MMPost:KMM_Sysfile_uploadFiles parameters:parmDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data = weakSelf.imageModel.tempFileData;
        if (data) {
            NSString * fileName = [weakSelf uploadFileName];
            [formData appendPartWithFileData:data name:@"files" fileName:fileName mimeType:@"image/png"];
        }
        
    } progress:^(NSProgress * _Nonnull progress) {
        
        long long totalBytesWritten = progress.completedUnitCount;
        long long totalBytesExpectedToWrite = progress.totalUnitCount;
        if (totalBytesExpectedToWrite == 0) {
            
            totalBytesExpectedToWrite = CGFLOAT_MAX;
        }
        CGFloat pro = (totalBytesWritten*1.0) / totalBytesExpectedToWrite;
        /*保证是 0~ 1 的范围 **/
        pro = MIN(MAX(pro, 0), 1);
        
        CGFloat hasFinishedW = pro * weakSelf.MM_w;
        weakSelf.maskView.MM_w = weakSelf.MM_w - hasFinishedW;
        weakSelf.maskView.MM_x = hasFinishedW;
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject) {
        
        if (responseObject) {
            
            NSDictionary *requestDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            if ([requestDic isKindOfClass:[NSDictionary class]]) {
                id responeDic = requestDic[@"data"];
                if ([responeDic isKindOfClass:[NSArray class]]) {
                    
                    NSArray *picArr = (NSArray *)responeDic;
                    
                    if (picArr.count > 0) {
                        NSDictionary *picDic = picArr.firstObject;
                        
                        if (picDic[@"url"]) {
                            weakSelf.imageModel.img = picDic[@"url"];
                            weakSelf.imageModel.img_id = picDic[@"id"];
                            weakSelf.imageModel.uploadStatusType = MMUploadViewTypeSucessed;
                            
                            [weakSelf updatePicData:picArr];
                            
                            if (weakSelf.successBlock) {
                                weakSelf.successBlock(picDic);
                            }
                        }else {
                            weakSelf.errorBtn.hidden = NO;
                            weakSelf.imageModel.uploadStatusType = MMUploadViewTypeFail;
                            if (weakSelf.failBlock) {
                                weakSelf.failBlock(@"上传失败");
                            }
                        }
                        
                    }else {
                        weakSelf.errorBtn.hidden = NO;
                        weakSelf.imageModel.uploadStatusType = MMUploadViewTypeFail;
                        if (weakSelf.failBlock) {
                            weakSelf.failBlock(@"上传失败");
                        }
                    }
                    
                    
                }
                
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull operation, NSError * _Nonnull error) {
        
        weakSelf.errorBtn.hidden = NO;
        weakSelf.imageModel.uploadStatusType = MMUploadViewTypeFail;
        if (weakSelf.failBlock) {
            weakSelf.failBlock(error.localizedDescription);
        }
    }];
    
}

- (void)updatePicData:(NSArray *)picData {
    
    NSMutableDictionary *parmDic = [NSMutableDictionary dictionary];
    parmDic[@"sku_id"] = self.imageModel.sku_id;
    parmDic[@"skuFiles"] = picData;
    
    [MM_Http postRequestURLStr:KMM_Spu_Files withDic:parmDic success:^(NSDictionary * _Nonnull requestDic, NSString * _Nonnull msg) {
        
        id responeDic = requestDic[@"data"];
        
        if ([responeDic isKindOfClass:[NSArray class]]) {
            
            NSArray *picArr = (NSArray *)responeDic;
            
            if (picArr.count > 0) {
                
                self.imageModel.picParmDic = picArr.firstObject;
            }else {
                self.errorBtn.hidden = NO;
                self.imageModel.uploadStatusType = MMUploadViewTypeFail;
                if (self.failBlock) {
                    self.failBlock(@"上传失败");
                }
            }
            
        } else {
            self.errorBtn.hidden = NO;
            self.imageModel.uploadStatusType = MMUploadViewTypeFail;
            if (self.failBlock) {
                self.failBlock(@"上传失败");
            }
        }
                
    } failure:^(NSString * _Nonnull errorInfo, NSString * _Nonnull status) {
        NSLog(@"errorInfoerrorInfoerrorInfo == %@",errorInfo);
        
        self.errorBtn.hidden = NO;
        self.imageModel.uploadStatusType = MMUploadViewTypeFail;
        if (self.failBlock) {
            self.failBlock(@"上传失败");
        }
    }];
}

#pragma mark - 触发点击方法
/**
 *  图片点击
 */
- (void)imageTapClick {
    
    if (self.tapPicBlock) {
        self.tapPicBlock();
    }
}

/**
 *  删除图片
 */
- (void)deleteClick {
    
    if (self.deletePicBlock) {
        self.deletePicBlock(self);
    }
    
}

/**
 *  获得唯一标示，当前的名字
 *
 *  @return
 */
- (NSString *)uploadFileName {
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd_HH:mm:ss:SSS"];
    NSString *date = [formatter stringFromDate:[NSDate date]];
    return [date stringByAppendingString:@".png"];
    
}

/**
 *  清空picView的 请求
 */
- (void)clearnPicViewRequest {
    
}

/**
 *  清空picView的数据
 */
- (void)clearnPicViewData {
    self.imageModel = nil;
}

/**
 *  错误的点击
 */
- (void)errorClick {
    
    if (self.errorPicBlock) {
        self.errorPicBlock();
    }
}

- (void)setSuccessBlock:(MMUploadPicViewSuccessBlock)successBlock
              failBlock:(MMUploadPicViewFailBlock)failBlock
            tapPicBlock:(MMUploadPicViewTapClickBlock)tapPicBlock
         deletePicBlock:(MMUploadPicViewTapDeleteBlock)deletePicBlock
          errorPicBlock:(MMUploadPicViewTapErrorBlock)errorPicBlock {
    
    self.successBlock   = successBlock;
    self.failBlock      = failBlock;
    self.tapPicBlock    = tapPicBlock;
    self.deletePicBlock = deletePicBlock;
    self.errorPicBlock  = errorPicBlock;
}

@end
